<template>
  <div class="page-container">
    <el-row :gutter="20" class="page-row">
      <el-col :span="10" style="height: 100%;">
        <!-- 标签列表 -->
        <el-card class="page-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <div class="header-title">
                <el-icon><Collection /></el-icon>
                <span>标签列表</span>
              </div>
              <el-button type="primary" @click="handleAddTag">
                <el-icon><Plus /></el-icon>新增标签
              </el-button>
            </div>
          </template>
          <div class="scroll-container tag-list">
            <div
              v-for="tag in tags"
              :key="tag.id"
              class="tag-item"
              :class="{ active: selectedTagId === tag.id }"
              @click="handleTagSelect(String(tag.id))">
              <div class="tag-content">
                <el-icon><Collection /></el-icon>
                <span class="tag-name">{{ tag.name }}</span>
                <el-tag size="small" type="info" class="tag-count" effect="plain">
                  {{ tag.ruleCount || 0 }}个规则
                </el-tag>
              </div>
              <div class="tag-footer">
                <span class="tag-creator">
                  <el-icon><User /></el-icon>
                  {{ tag.creator }}
                </span>
                <el-tooltip
                  :content="tag.description"
                  placement="top"
                  :show-after="500">
                  <el-icon class="info-icon"><InfoFilled /></el-icon>
                </el-tooltip>
              </div>
            </div>
            <el-empty v-if="!tags.length" description="暂无标签" />
          </div>
        </el-card>
      </el-col>

      <el-col :span="14" style="height: 100%;">
        <!-- 规则列表 -->
        <el-card v-if="selectedTagId" class="page-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <div class="header-title">
                <el-icon><Setting /></el-icon>
                <span>{{ selectedTag?.name }} - 规则配置</span>
                <el-tag type="success" effect="plain" class="rule-count">
                  共 {{ rules.length }} 个规则
                </el-tag>
              </div>
              <el-button type="primary" @click="handleAddRule">
                <el-icon><Plus /></el-icon>新增规则
              </el-button>
            </div>
          </template>
          <div class="scroll-container rule-list-wrapper">
            <el-table 
              :data="rules" 
              style="width: 100%"
              :header-cell-style="{ background: 'var(--el-fill-color-light)' }"
              border>
              <el-table-column prop="metricName" label="指标名称" min-width="120" />
              <el-table-column prop="metricType" label="指标类型" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.metricType === 'UPSTREAM' ? 'success' : 'warning'" size="small">
                    {{ scope.row.metricType === 'UPSTREAM' ? '上行' : '下行' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="规则配置" min-width="200">
                <template #default="scope">
                  <div class="rule-config">
                    <span class="rule-expression">
                      {{ scope.row.metricName }} {{ scope.row.condition }} {{ scope.row.threshold }}
                    </span>
                    <el-tag 
                      size="small" 
                      :type="getDurationTagType(scope.row.duration)"
                      effect="plain">
                      持续 {{ scope.row.duration }} 秒
                    </el-tag>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="priority" label="优先级" width="100">
                <template #default="scope">
                  <el-tag 
                    :type="getPriorityTagType(scope.row.priority)" 
                    size="small"
                    effect="plain">
                    P{{ scope.row.priority }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="enabled" label="状态" width="100" align="center">
                <template #default="scope">
                  <el-switch
                    v-model="scope.row.enabled"
                    :active-text="scope.row.enabled ? '已启用' : '已禁用'"
                    @change="handleRuleStatusChange(scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" fixed="right">
                <template #default="scope">
                  <el-button-group>
                    <el-button 
                      size="small" 
                      type="primary" 
                      plain
                      @click="handleEditRule(scope.row)">
                      <el-icon><Edit /></el-icon>
                    </el-button>
                    <el-button 
                      size="small" 
                      type="danger" 
                      plain
                      @click="handleDeleteRule(scope.row)">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </el-button-group>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
        <el-empty v-else description="请选择左侧标签以配置规则" />
      </el-col>
    </el-row>

    <!-- 标签编辑对话框 -->
    <el-dialog
      v-model="tagDialogVisible"
      :title="tagDialogType === 'add' ? '新增标签' : '编辑标签'"
      width="500px"
      destroy-on-close>
      <el-form 
        ref="tagFormRef"
        :model="tagForm" 
        :rules="tagRules"
        label-width="100px"
        status-icon>
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="tagForm.name" placeholder="请输入标签名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="tagForm.description" 
            type="textarea" 
            placeholder="请输入标签描述"
            :rows="3" />
        </el-form-item>
        <el-form-item label="创建人" prop="creator">
          <el-input v-model="tagForm.creator" placeholder="请输入创建人" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="tagDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleTagSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 规则编辑对话框 -->
    <el-dialog
      v-model="ruleDialogVisible"
      :title="ruleDialogType === 'add' ? '新增规则' : '编辑规则'"
      width="600px"
      destroy-on-close>
      <el-form 
        ref="ruleFormRef"
        :model="ruleForm" 
        :rules="ruleRules"
        label-width="100px"
        status-icon>
        <el-form-item label="指标名称" prop="metricName">
          <el-input 
            v-model="ruleForm.metricName" 
            placeholder="基于多引擎链路监控系统录入名称"
            clearable />
        </el-form-item>
        <el-form-item label="指标类型" prop="metricType">
          <el-radio-group v-model="ruleForm.metricType">
            <el-radio-button label="UPSTREAM">上行指标</el-radio-button>
            <el-radio-button label="DOWNSTREAM">下行指标</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="条件" prop="condition">
          <div class="condition-group">
            <div class="condition-row">
              <span class="condition-category">基础比较：</span>
              <el-radio-group v-model="ruleForm.condition" class="condition-options">
                <el-radio label=">">大于</el-radio>
                <el-radio label="<">小于</el-radio>
                <el-radio label="=">等于</el-radio>
                <el-radio label=">=">大于等于</el-radio>
                <el-radio label="<=">小于等于</el-radio>
              </el-radio-group>
            </div>
            <div class="condition-row">
              <span class="condition-category">范围条件：</span>
              <el-radio-group v-model="ruleForm.condition" class="condition-options">
                <el-radio label="between">区间内</el-radio>
                <el-radio label="not_between">区间外</el-radio>
              </el-radio-group>
            </div>
            <div class="condition-row">
              <span class="condition-category">特殊条件：</span>
              <el-radio-group v-model="ruleForm.condition" class="condition-options">
                <el-radio label="null">无数据</el-radio>
                <el-radio label="not_null">有数据</el-radio>
              </el-radio-group>
            </div>
          </div>
        </el-form-item>
        <el-form-item
          label="阈值"
          prop="threshold"
          v-if="!['null', 'not_null'].includes(ruleForm.condition)"
        >
          <el-input-number
            v-model="ruleForm.threshold"
            :precision="2"
            :step="0.1"
            style="width: 180px"
          />
          <template v-if="ruleForm.condition === 'between' || ruleForm.condition === 'not_between'">
            <span class="mx-2">至</span>
            <el-input-number
              v-model="ruleForm.threshold2"
              :precision="2"
              :step="0.1"
              style="width: 180px"
            />
          </template>
        </el-form-item>
        <el-form-item label="持续时间" prop="duration">
          <el-input-number
            v-model="ruleForm.duration"
            :min="15"
            :step="5"
            style="width: 180px"
          >
            <template #suffix>秒</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-slider
            v-model="ruleForm.priority"
            :min="0"
            :max="100"
            :step="10"
            show-stops
            :marks="{
              0: '低',
              50: '中',
              100: '高'
            }"
          />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch v-model="ruleForm.enabled" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="ruleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRuleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  Edit, 
  Delete, 
  Collection, 
  InfoFilled, 
  Setting,
  User 
} from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import axios from 'axios'
import '../styles/global.css'

// 配置axios默认值
axios.defaults.baseURL = 'http://localhost:8080'

interface Tag {
  id?: number
  name: string
  description?: string
  creator: string
  ruleCount?: number
}

interface RuleForm {
  id?: number
  tagId: number
  metricName: string
  metricType: string
  condition: string
  threshold: number
  threshold2?: number  // 添加第二个阈值，用于区间条件
  duration: number
  priority: number
  enabled: boolean
}

// 表单校验规则
const tagRules = {
  name: [
    { required: true, message: '请输入标签名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  creator: [
    { required: true, message: '请输入创建人', trigger: 'blur' }
  ]
} as FormRules

const ruleRules = {
  metricName: [
    { required: true, message: '请输入多引擎链路监控系统指标名称', trigger: 'blur' }
  ],
  metricType: [
    { required: true, message: '请选择指标类型', trigger: 'change' }
  ],
  condition: [
    { required: true, message: '请选择条件', trigger: 'change' }
  ],
  threshold: [
    { required: true, message: '请输入阈值', trigger: 'blur' }
  ],
  duration: [
    { required: true, message: '请输入持续时间', trigger: 'blur' },
    { type: 'number', min: 15, message: '持续时间必须大于等于15秒', trigger: 'blur' }
  ]
} as FormRules

// 标签相关
const tags = ref<Tag[]>([])
const selectedTagId = ref<number>()
const selectedTag = computed(() => tags.value.find(t => t.id === selectedTagId.value))
const tagDialogVisible = ref(false)
const tagDialogType = ref<'add' | 'edit'>('add')
const tagFormRef = ref<FormInstance>()
const tagForm = ref<Tag>({
  name: '',
  description: '',
  creator: ''
})

// 规则相关
const rules = ref<RuleForm[]>([])
const ruleDialogVisible = ref(false)
const ruleDialogType = ref<'add' | 'edit'>('add')
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<RuleForm>({
  tagId: 0,
  metricName: '',
  metricType: 'DOWNSTREAM',
  condition: '>',
  threshold: 0,
  threshold2: 0,
  duration: 15,
  priority: 50,
  enabled: true
})

// 获取标签列表
const fetchTags = async () => {
  try {
    console.log('Fetching tags...')
    const response = await axios.get('/api/rtc/tags')
    console.log('Tags response:', response.data)
    tags.value = response.data
  } catch (error) {
    console.error('获取标签列表失败:', error)
    ElMessage.error('获取标签列表失败')
  }
}

// 获取规则列表
const fetchRules = async (tagId: number) => {
  try {
    const response = await axios.get(`/api/rtc/rules/tag/${tagId}`)
    rules.value = response.data
  } catch (error) {
    ElMessage.error('获取规则列表失败')
  }
}

// 标签相关操作
const handleAddTag = () => {
  tagDialogType.value = 'add'
  tagForm.value = {
    name: '',
    description: '',
    creator: ''
  }
  tagDialogVisible.value = true
}

const handleTagSelect = (index: string) => {
  const tagId = Number(index)
  selectedTagId.value = tagId
  if (tagId) {
    fetchRules(tagId)
  }
}

const handleTagSubmit = async () => {
  if (!tagFormRef.value) return
  
  await tagFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (tagDialogType.value === 'add') {
          await axios.post('/api/rtc/tags', tagForm.value)
          ElMessage.success('添加成功')
        } else {
          await axios.put(`/api/rtc/tags/${selectedTagId.value}`, tagForm.value)
          ElMessage.success('更新成功')
        }
        tagDialogVisible.value = false
        fetchTags()
      } catch (error) {
        ElMessage.error(tagDialogType.value === 'add' ? '添加失败' : '更新失败')
      }
    }
  })
}

// 规则相关操作
const handleAddRule = () => {
  if (!selectedTagId.value) {
    ElMessage.warning('请先选择标签')
    return
  }
  
  ruleDialogType.value = 'add'
  ruleForm.value = {
    tagId: selectedTagId.value,
    metricName: '',
    metricType: 'DOWNSTREAM',
    condition: '>',
    threshold: 0,
    threshold2: 0,
    duration: 15,
    priority: 50,
    enabled: true
  }
  ruleDialogVisible.value = true
}

const handleEditRule = (rule: RuleForm) => {
  ruleDialogType.value = 'edit'
  ruleForm.value = { ...rule }
  ruleDialogVisible.value = true
}

const handleDeleteRule = async (rule: RuleForm) => {
  try {
    await ElMessageBox.confirm('确定要删除该规则吗？', '提示', {
      type: 'warning'
    })
    await axios.delete(`/api/rtc/rules/${rule.id}`)
    ElMessage.success('删除成功')
    if (selectedTagId.value) {
      fetchRules(selectedTagId.value)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleRuleStatusChange = async (rule: RuleForm) => {
  try {
    await axios.put(`/api/rtc/rules/${rule.id}`, rule)
    ElMessage.success('状态更新成功')
  } catch (error) {
    ElMessage.error('状态更新失败')
    rule.enabled = !rule.enabled // 恢复状态
  }
}

const handleRuleSubmit = async () => {
  if (!ruleFormRef.value) return

  await ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (ruleDialogType.value === 'add') {
          await axios.post('/api/rtc/rules', ruleForm.value)
          ElMessage.success('添加成功')
        } else {
          await axios.put(`/api/rtc/rules/${ruleForm.value.id}`, ruleForm.value)
          ElMessage.success('更新成功')
        }
        ruleDialogVisible.value = false
        if (selectedTagId.value) {
          fetchRules(selectedTagId.value)
        }
      } catch (error) {
        ElMessage.error(ruleDialogType.value === 'add' ? '添加失败' : '更新失败')
      }
    }
  })
}

// 辅助函数
const getDurationTagType = (duration: number) => {
  if (duration <= 5) return 'success'
  if (duration <= 15) return 'warning'
  return 'danger'
}

const getPriorityTagType = (priority: number) => {
  if (priority <= 30) return 'info'
  if (priority <= 70) return 'warning'
  return 'danger'
}

// 初始化
onMounted(() => {
  console.log('Component mounted, fetching tags...')
  fetchTags()
})
</script>

<style scoped>
.tag-management {
  padding: 20px;
  height: calc(100vh - 84px);
  width: 100vw;
  max-width: 100%;
  margin: 0;
  box-sizing: border-box;
  background-color: var(--el-fill-color-blank);
}

.el-row {
  margin: 0 !important;
  width: 100%;
}

.tag-list-card,
.rule-list-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  margin: 0;
  width: 100%;
}

.tag-list {
  flex: 1;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  overflow-y: auto;
  overflow-x: hidden;
}

.tag-item {
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  min-width: 200px;
}

.tag-item:hover {
  border-color: var(--el-color-primary);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.tag-item.active {
  background: var(--el-color-primary-light-9);
  border-color: var(--el-color-primary);
}

.tag-item.active::before {
  content: '';
  position: absolute;
  left: -2px;
  top: 0;
  bottom: 0;
  width: 4px;
  background-color: var(--el-color-primary);
  border-radius: 2px;
}

.tag-content {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
  min-height: 32px;
}

.tag-name {
  flex: 1;
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  line-height: 1.4;
  word-break: break-word;
}

.tag-count {
  font-size: 12px;
  padding: 0 8px;
  height: 22px;
  line-height: 22px;
  border-radius: 11px;
}

.tag-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 13px;
  color: var(--el-text-color-secondary);
}

.tag-creator {
  display: flex;
  align-items: center;
  gap: 4px;
}

.info-icon {
  color: var(--el-text-color-secondary);
  font-size: 16px;
  cursor: help;
  transition: color 0.3s;
}

.info-icon:hover {
  color: var(--el-color-primary);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.header-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
}

.header-title .el-icon {
  font-size: 18px;
  color: var(--el-color-primary);
}

.header-title .rule-count {
  margin-left: 12px;
  font-weight: normal;
}

.rule-list-wrapper {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  width: 100%;
}

.rule-list-wrapper::-webkit-scrollbar {
  width: 6px;
}

.rule-list-wrapper::-webkit-scrollbar-thumb {
  background-color: var(--el-border-color);
  border-radius: 3px;
}

.rule-list-wrapper::-webkit-scrollbar-track {
  background-color: var(--el-fill-color-blank);
}

.rule-config {
  display: flex;
  align-items: center;
  gap: 8px;
}

.rule-expression {
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
  padding: 4px 8px;
  background: var(--el-fill-color-light);
  border-radius: 4px;
  font-size: 13px;
  color: var(--el-text-color-primary);
}

:deep(.el-card) {
  width: 100%;
  height: 100%;
  border: 1px solid var(--el-border-color-lighter);
  box-shadow: none;
}

:deep(.el-card:hover) {
  box-shadow: var(--el-box-shadow-light);
}

:deep(.el-table) {
  width: 100% !important;
  --el-table-border-color: var(--el-border-color-lighter);
  --el-table-border: 1px solid var(--el-table-border-color);
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: var(--el-fill-color-light) !important;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 8px 0;
}

:deep(.el-table .cell) {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 20px;
  border-top: 1px solid var(--el-border-color-lighter);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-slider__marks-text) {
  margin-top: 8px;
  color: var(--el-text-color-secondary);
}

.condition-group {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.condition-row {
  display: flex;
  align-items: center;
  gap: 12px;
}

.condition-category {
  width: 100px;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.condition-options {
  flex: 1;
}

.mx-2 {
  margin: 0 12px;
}

:deep(.el-radio) {
  margin-right: 20px;
  margin-bottom: 8px;
}

:deep(.el-radio__label) {
  font-size: 14px;
}
</style> 